// pages/splash/splash.js

const App = getApp()
import Kits from '../../utils/kits'
import Util from '../../utils/util'
const CryptoJS = require('crypto-js')

Page({
  data: {
    init: false,
    loading: false,
    conf: {},

    sld: false,

    apply: false,
    mer: {},


    service: false,

    keyl: false,
    key: '',
    pwd: '',


    mobl: false,
    butText: '验证码',
    butDisabled: false,

    mob: '',
    vinfo: '',
    vcode: '',

    interval: undefined,
    sec: 0,
  },
  onLoad() {
    App.doPost({
      uri: '/app/base/data/config',
      body: {},
      fnSucc: resp => {

        this.setData({
          // init:true,
          conf: resp.data
        })

        let sld = wx.getStorageSync('App.Sld') !== 'true'
        if (!sld) {
          this.waitForReady()
        } else {
          this.setData({
            sld: sld
          })
        }
      }
    })

  },
  waitForReady() {
    console.log('wait user init : ', App.Global)
    if (App.Global.OpenId) {
      // App.Global.User.name && App.Global.User.merchant.state == 1  原判断条件
      if (App.Global.User.name && App.Global.User.merchant.state == 1) {
        wx.redirectTo({
          url: '/pages/index/index',
        })
        return
      }
      if (App.Global.User.name && App.Global.User.merchant.state == 0) {
        // wx.redirectTo({
        //   url: '/pages/funcs/apply',
        // })
        this.setData({
          apply: true,
          mer: App.Global.User.merchant
        })
        return
      }

      this.setData({
        init: true
      })

    }
    // 原逻辑
    else {
      setTimeout(() => {
        this.waitForReady()
      }, 200);
    }
  },
  toApply() {
    wx.redirectTo({
      url: '/pages/funcs/apply',
    })
  },

  doClear() {
    wx.showModal({
      title: '温馨提示',
      cancelText: '点错了',
      confirmText: '继续撤销',
      confirmColor: '#e54d42',
      content: '是否撤销并清空入驻信息？',
      success: (res) => {
        if (res.confirm) {
          App.doPost({
            uri: '/app/merchant/apply/clear',
            body: {},
            fnSucc: () => {
              wx.setStorageSync('App.Uid', '')
              wx.setStorageSync('App.Token', 'Guest')
              wx.setStorageSync('App.Name', '')
              wx.setStorageSync('App.User', '{}')
              wx.setStorageSync('App.Users', '[]')
              App.Global.User = {}
              App.Global.Token = 'Guest'
              wx.reLaunch({
                url: '/pages/splash/splash',
              })
            }
          })
        }
      }
    })
  },
  toPage(e) {
    wx.navigateTo({
      url: e.currentTarget.dataset.uri
    })
  },
  toAgreement() {
    wx.navigateTo({
      url: `/pages/funcs/web?url=${this.data.conf.web.yhxy}`,
    })
  },
  toPolicy() {
    wx.navigateTo({
      url: `/pages/funcs/web?url=${this.data.conf.web.yszc}`,
    })
  },
  toMchJoin() {
    const url = encodeURIComponent('https://h5.hangzhouyizuke.com/service/#/?type=b&login=0')
    wx.navigateTo({
      url: `/pages/funcs/web?url=${url}`,
    })
  },
  doService() {
    this.setData({
      service: true
    })
  },
  doPreview() {
    wx.previewImage({
      urls: ['https://cdn.hangzhouyizuke.com/res/app/corpwx_service.jpg?t=1'],
    })
  },
  doPass() {
    wx.setStorageSync('App.Sld', 'true')
    this.setData({
      sld: false
    })
    this.waitForReady()
  },
  doAuthCode() {
    this.setData({
      keyl: true,
      key: '',
      pwd: ''
    })
  },
  hideModal() {
    this.setData({
      keyl: false,
      mobl: false,
      service: false,
    })
  },
  doKeyLogin() {
    if (!this.data.key) {
      Util.Notify.warn(`请填写用户账号`)
      return
    }
    if (!this.data.pwd) {
      Util.Notify.warn(`请填写授权密码`)
      return
    }
    this.setData({
      loading: true
    })
    let ppwd = CryptoJS.SHA1(Kits.reverseString(this.data.pwd)).toString().toUpperCase()
    App.doPost({
      uri: '/app/user/account/key/signin',
      body: {
        appid: App.Global.AppId,
        ouid: App.Global.OpenId,
        key: this.data.key,
        pwd: ppwd,
      },
      fnSucc: (resp) => {
        let user = resp.data

        wx.setStorageSync('App.Uid', user.id)
        wx.setStorageSync('App.Token', user.token)
        wx.setStorageSync('App.Name', user.name)
        wx.setStorageSync('App.User', JSON.stringify(user))
        App.Global.User = user
        App.Global.Token = user.token
        Util.Toast.succ('登录成功')
        setTimeout(() => {
          wx.redirectTo({
            url: `/pages/index/index`,
          })
        }, 800);
      },
      fnFail: resp => {
        Util.Notify.error(`[${resp.stat.err}] ${resp.stat.msg}`)
      },
      fnComp: () => {
        this.setData({
          loading: false,
        })
      }
    })
  },
  // onPhoneNumber(e) {
  //   console.log(e)
  //   if (!e.detail.code) {
  //     return
  //   }
  //   this.setData({
  //     loading: true
  //   })
  //   App.doPost({
  //     uri: '/app/user/account/wxmn/clerk/mob/login',
  //     body: {
  //       appid: App.Global.AppId,
  //       openid: App.Global.OpenId,
  //       code: e.detail.code,
  //     },
  //     fnSucc: (resp) => {
  //       let user = resp.data.user
  //       wx.setStorageSync('App.Uid', user.id)
  //       wx.setStorageSync('App.Token', user.token)
  //       wx.setStorageSync('App.Name', user.name)
  //       wx.setStorageSync('App.User', JSON.stringify(user))
  //       App.Global.User = user
  //       App.Global.Token = user.token
  //       Util.Toast.succ('登录成功')
  //       setTimeout(() => {
  //         wx.redirectTo({
  //           url: `/pages/index/index`,
  //         })
  //       }, 800);
  //     },
  //     fnFail: resp => {
  //       Util.Notify.error(`[${resp.stat.err}] ${resp.stat.msg}`)
  //     },
  //     fnComp: () => {
  //       this.setData({
  //         loading: false,
  //       })
  //     }
  //   })
  // },


  execGetVcode() {
    if (this.data.mob.length != 11) {
      return
    }
    if (this.data.butDisabled) {
      return
    }
    this.setData({
      loading: true,
      butDisabled: true
    })
    // 确认获取验证码请求
    App.doPost({
      uri: '/app/base/tool/sms/captcha',
      body: {
        mob: this.data.mob,
        type: 'MchLogin'
      },
      fnSucc: resp => {
        this.setData({
          sec: resp.data.limit,
          vinfo: resp.data.vinfo,
        })
        let int = setInterval(() => {
          if (this.data.sec <= 1) {
            clearInterval(this.data.interval)
            this.setData({
              sec: 0,
              butText: '验证码',
              butDisabled: false,
              interval: undefined
            })
            return
          }
          this.data.sec = this.data.sec - 1
          this.setData({
            sec: this.data.sec,
            butText: `${this.data.sec} 秒`
          })
        }, 1000);
        this.setData({
          interval: int
        })
        if (App.Global.Debug && resp.data.vcode) {
          wx.showToast({
            icon: 'none',
            title: '测试账号，验证码已自动填写'
          })
          this.setData({
            vcode: resp.data.vcode
          })
        } else {
          wx.showToast({
            title: '验证码已发送'
          })
        }

      },
      fnFail: resp => {
        Util.Notify.error(`[${resp.stat.err}] ${resp.stat.msg}`)
        this.setData({
          butDisabled: false,
        })
      },
      fnComp: () => {
        this.setData({
          loading: false,
        })
      }
    })
  },
  doMobile() {
    this.setData({
      keyl: false,
      mobl: true,

      mob: '',
      vinfo: '',
      vcode: '',

      interval: undefined,
      sec: 0,
    })
  },

  // 手机号确认登录
  doMobileLogin() {
    if (!this.data.mob) {
      Util.Notify.warn(`请填写手机号`)
      return
    }
    if (!this.data.vinfo) {
      Util.Notify.warn(`请获取验证码`)
      return
    }
    if (!this.data.vcode) {
      Util.Notify.warn(`请填写验证码`)
      return
    }
    this.setData({
      loading: true
    })
    console.log(this.data, "data数据")
    App.doPost({
      uri: '/app/user/account/wxmn/clerk/mob/signin',
      body: {
        appid: App.Global.AppId,
        openid: App.Global.OpenId,
        mob: this.data.mob,
        vinfo: this.data.vinfo,
        vcode: this.data.vcode,
      },
      fnSucc: (resp) => {
        let user = resp.data.user
          wx.setStorageSync('App.Uid', user.id)
          wx.setStorageSync('App.Token', user.token)
          wx.setStorageSync('App.Name', user.name)
          wx.setStorageSync('App.User', JSON.stringify(user))
          App.Global.User = user
          App.Global.Token = user.token
        // console.log(resp.data,"appglobal")
        if (resp.data.user.name &&resp.data.user.merchant.state == 0) {
          // wx.redirectTo({
          //   url: '/pages/funcs/apply',
          // })
          this.setData({
            mobl: false,
            apply: true,
            mer: resp.data.user.merchant
          })
          return
        } else {
          Util.Toast.succ('登录成功')
          this.setData({
           
          })
          setTimeout(() => {
            wx.redirectTo({
              url: `/pages/index/index`,
            })
          }, 800);
        }
      },
      fnFail: resp => {
        Util.Notify.error(`[${resp.stat.err}] ${resp.stat.msg}`)
      },
      fnComp: () => {
        this.setData({
          loading: false,
        })
      }
    })
  },
})